package io.litchi.auth.Infrastructure.handler;

import io.litchi.auth.Infrastructure.securityentity.LitchiUser;
import io.litchi.auth.domain.entity.auth.User;
import io.litchi.auth.domain.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;

/**
 *
 * jwt 转换器
 * @author helang
 * @since 2025-11-21
 */
@Component
@RequiredArgsConstructor
public class LitchiJwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
    private final UserRepository userRepository;

    @Override
    public AbstractAuthenticationToken convert(Jwt jwt) {
        // 1. 从 JWT 获取用户名（sub）
        String username = jwt.getSubject();

        // 2. 从数据库加载用户
        User user = userRepository.findByUsername(username, User.class).orElse(new User());

        // 3. 构造 LitchiUser
        LitchiUser userDetails = LitchiUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password("")
                .build();

        // 4. 返回 UsernamePasswordAuthenticationToken（principal = LitchiUser）
        return new UsernamePasswordAuthenticationToken(
                userDetails,
                jwt,
                userDetails.getAuthorities()
        );
    }
}